package com.sea.app.module.identity.domain.algorithm;

import com.sea.app.common.excrption.BusinessException;
import com.sea.app.common.excrption.SystemException;
import com.sea.app.common.kit.Dates;
import com.sea.app.common.kit.Strings;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.util.Date;

/**
 * Created by 31417 on 2017/4/26.
 */
public class JwtToken {
    public static final String HEADER_PREFIX = "Bearer ";


    private Claims claims;

    private JwtToken(String token, String key) {
        Strings s = Strings.on(token)
                .isBlank(strings -> {
                    throw BusinessException.on("validate.tokenIsBlank", "token不合法！");
                })
                .removeStart(HEADER_PREFIX.length());
        this.claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(s.toString())
                .getBody();
    }

    public static JwtToken on(String token, String key) {
        return new JwtToken(token, key);
    }

    public boolean validateToken(String ip) {
        String name = getSubject();
        Date expiration = claims.getExpiration();
        Date issuedAt = claims.getIssuedAt();
        String id = claims.getId();
        if (name == null || expiration == null || issuedAt == null || id == null) {
            throw SystemException.on("token.validateFail", "token错误!");
        }
        return Dates.now().between(issuedAt, expiration)
                &&ip.equalsIgnoreCase((String) claims.get("ip"));
    }

    public String getId() {
        return claims.getId();
    }

    public String getSubject() {
        return claims.getSubject();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof JwtToken){
            return ((JwtToken)obj).getId().equals(getId());
        }
        return super.equals(obj);
    }
}
